package com.hframe.taglib.json;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import javax.servlet.jsp.JspException;
import java.util.Iterator;

public class JsonArrayTag extends JsonBaseTag {
	private static final long serialVersionUID = 1L;
	Iterator<JsonElement> iter = null;
	JsonElement element = null;

	@Override
	public int doStartTag() throws JspException {
		try {
			if (this.json != null)
				this.setObJson(new JsonParser().parse(this.json));
			else {
				JsonBaseTag parent = getParent();
				if (parent != null)
					this.setObJson(parent.getObJson());
			}

			GetJson();
			if (null != obJson && obJson.isJsonArray()) {
				iter = obJson.getAsJsonArray().iterator();
			}
			outJson();
			doAfterBody();
		} catch (Exception e) {
		}
		return super.doStartTag();
	}

	@Override
	public int doEndTag() throws JspException {
		return super.doEndTag();
	}

	@Override
	public int doAfterBody() throws JspException {
		element = null;
		if (null != iter && iter.hasNext()) {
			element = iter.next();
			return EVAL_BODY_AGAIN;
		} else {
			return SKIP_BODY;
		}
	}

	@Override
	protected JsonElement getObJson() {
		return element;
	}

}
